package com.mvd.app.ac2019;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iceteck.silicompressorr.SiliCompressor;
import com.kongzue.dialog.v3.TipDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac2020.DiaoDuActivity;
import com.mvd.app.activity.BaseActivity;
import com.mvd.app.activity.DaiJianCarsActivity;
import com.mvd.app.activity.PermissionUtils;
import com.mvd.app.activity.SettingActivity;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.UserAccountModel;
import com.mvd.app.model.VideoUploadModel;
import com.mvd.app.upload.MyUploadService;
import com.werb.permissionschecker.PermissionChecker;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 新版进入后的第一个页面
 * 导航页
 * 四个大按钮
 **/
public class FirstActivity extends BaseActivity {

    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.ac_first_waijian)
    TextView acFirstWaijian;
    @BindView(R.id.ac_login_view_m)
    TextView acLoginViewM;
    @BindView(R.id.ac_first_dipandongtai)
    TextView acFirstDipandongtai;
    @BindView(R.id.ac_first_lushi)
    TextView acFirstLushi;
    @BindView(R.id.ac_login_view_m123)
    TextView acLoginViewM123;
    @BindView(R.id.ac_first_setting)
    TextView acFirstSetting;
    @BindView(R.id.ac_first_digou_item)
    TextView acFirstDigouItem;
    @BindView(R.id.ac_first_digou)
    TextView acFirstDigou;

    private FirstActivity instance;
    private String Login_name = "", login_IDNumber, login_username;//当前登录的检测员的名字
    private UserAccountModel UserAccountModel_model;
    private int CHECK_MODE_CURRENT = 0;
    public static String[] permissionArray = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.RECORD_AUDIO,
    };

    private PermissionChecker permissionChecker;
    List<VideoUploadModel> VideoUploadModelList = new ArrayList<>();
    private String currentOutputVideoPath = "";//压缩后的视频地址
    public static final String PATH =
            Environment.getExternalStorageDirectory().getAbsolutePath() + "/apeng/";
    private String videoTime = "";//获取视频时长
    private int videoWidth = 0;//获取视频的宽度
    private int videoHeight = 0;//获取视频的高度
    private int videoGotation = 0;//获取视频的角度
    private Bitmap mBitMap;
    private Double videoLength = 0.00;//视频时长 s
    private Handler handler = new Handler();
    MyRunnable myRunnable = new MyRunnable();//定义MyRunnable的对象；
    VideoUploadModel model = null;
//    private CustomProgressDialog mProcessingDialog;

//    private String mVideoPath = "";//原视频地址

    //    public static final String PATH =
//            Environment.getExternalStorageDirectory().getAbsolutePath() + "/apeng/";
    class MyRunnable implements Runnable {//内部类实现Runnable接口；

        @Override
        public void run() {//还是在Runnable重写的run()方法中更新界面；
//            text.setText("使用Handler更新了界面");
//            videoCompress(model.getSize(), model.getZp(), model);
//            video_VideoProcessor(model.getSize(), model.getZp(), model);
//            videoCompress_low(model.getSize(), model.getZp(), model);
//            videoCompress_medium(model.getSize(), model.getZp(), model);
            siliCompressor(model.getSize(), model.getZp(), model);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        ButterKnife.bind(this);
        instance = this;
        PermissionUtils.checkPermissionArray(this, permissionArray, 2);
        Login_name = getIntent().getExtras().getString("login_UserID", "");
        login_IDNumber = getIntent().getExtras().getString("login_IDNumber", "");
        login_username = getIntent().getExtras().getString("login_username", "");
        permissionChecker = new PermissionChecker(this); // initialize，must need

        if (permissionChecker.isLackPermissions(permissionArray)) {
            permissionChecker.requestPermissions();
            UtilsLog.e("请求录像权限失败===");
        } else {
            // startVideo();
            UtilsLog.e("请求录像权限成功===");
        }
        UserAccountModel_model = (UserAccountModel) getIntent().getSerializableExtra("UserAccountModel_model");
        UtilsLog.e("FirstActivity-----UserAccountModel_model===" + UserAccountModel_model.toString());
        String logStr = "\n" + "---FirstActivity----onCreate---" +
                "\n" + "UserAccountModel_model::" + UserAccountModel_model.toString();
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        bindService();

        getDB();
    }

    /**
     * Get db.
     * 查询数据库
     * 获取没有上传完成的视频
     */
    void getDB() {
        VideoUploadModelList = VideoUploadModel.find(VideoUploadModel.class, "statement=?", "0");
        if (VideoUploadModelList != null && VideoUploadModelList.size() > 0) {
//            initFile();
//            initVideo();
            for (int i = 0; i < VideoUploadModelList.size(); i++) {
                UtilsLog.e("VideoUploadModelList==" + i + "===" + VideoUploadModelList.get(i));
                String logStr22 = "\n" + "getDB()---录像路径---" + "\n" + "DB--data==" + "\n" +
                        VideoUploadModelList.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
                model = VideoUploadModelList.get(i);
//                videoCompress2(model.getSize(), model.getZp(), model);

//                String quality = SharedPreferencesUtils.getVideoQuality(this);
//                UtilsLog.e("FirstActivity---视频画质==" + quality);
//                if (SharedPreferencesUtils.getDongBeiVersion(this)) {
                new Thread() {

                    @Override
                    public void run() {
                        handler.post(myRunnable);//调用Handler.post方法；
                    }
                }.start();
//                video_VideoProcessor(model.getSize(), model.getZp(), model);
//                } else {
//                    videoCompress_no(model);
//                }
//                videoCompress_no(model);
//                if (quality.equals("低")) {
//                    videoCompress_low(model.getSize(), model.getZp(), model);
//                } else if (quality.equals("中")) {
//                    videoCompress_medium(model.getSize(), model.getZp(), model);
//                } else if (quality.equals("高")) {
//                    videoCompress_high(model.getSize(), model.getZp(), model);
//                } else if (quality.equals("无")) {
//                    videoCompress_no(model);
//                } else {
////                    startCompress(model);
//                }
            }
        }
        List<VideoUploadModel> VideoUploadModelList2 = new ArrayList<>();
        VideoUploadModelList2 = VideoUploadModel.find(VideoUploadModel.class, "statement=?", "0");
        if (VideoUploadModelList2 != null && VideoUploadModelList2.size() > 0) {
            for (int i = 0; i < VideoUploadModelList2.size(); i++) {
                long id = VideoUploadModelList2.get(i).getId();
                VideoUploadModel user = VideoUploadModel.findById(VideoUploadModel.class, id);
                user.delete();
            }
        }
    }

    class VideoCompressAsyncTask extends AsyncTask<String, String, String> {

        Context mContext;

        public VideoCompressAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... paths) {
            String filePath = null;
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(paths[0]);
                String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
                String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
                double widths = Integer.parseInt(width) * 0.9;
                double heights = Integer.parseInt(height) * 0.9;
                int videoWidth = new Double(widths).intValue();
                int videoHeight = new Double(heights).intValue();
                filePath = SiliCompressor.with(mContext).compressVideo(paths[0], paths[1], videoHeight, videoWidth, 1200000);
                Log.e("tag", "压缩完成了老哥，要开始上传啦~~");
                Log.e("tag", "压缩后的路径为===" + filePath);
                if (filePath != null) {
                    String logStr = "视频压缩完成，即将开始上传===22====";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    getDataUploadVideo2(model, filePath, "");
                } else {
                    String logStr = "视频压缩失败===22===";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                    getDataUploadVideo2(model, model.getSize(), "");
                }
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return filePath;

        }

        //得到压缩好的路径
        @Override
        protected void onPostExecute(String compressedFilePath) {
            super.onPostExecute(compressedFilePath);

        }
    }

    void siliCompressor(String videoUriString, String videoPath, final VideoUploadModel model) {
        String foder = Environment.getExternalStorageDirectory() + "/compress/";
        Log.e("tag", "压缩视频的文件夹为：" + foder);
        File file = new File(foder);
        if (!file.exists()) {
            file.mkdirs();
        }
        new VideoCompressAsyncTask(this).execute(videoUriString, file.getPath());
//        StringfilePath= SiliCompressor.with(BaseApplication.getSelf()).compressVideo(videoPath, destinationDirectory，outWidth，outHeight，bitrate);参数传入原视频videoPath和压缩后destinationDirectory存放的文件夹，返回压缩后图片绝对路径。横屏视频的outWidth宽度   outHeight高度   bitrate比特率（码率）越高数据大  体积越大一般450000
    }

    //上传视频
    private void getDataUploadVideo2(final VideoUploadModel carsInforModel, String filePath, String currentOutputVideoPath) {
        String video_url_path = "";
        if (!TextUtils.isEmpty(currentOutputVideoPath)) {
            video_url_path = currentOutputVideoPath;
        } else {
            video_url_path = filePath;
        }
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        String logStrqw = "\n" + "FirstActivity---外检上传视频--getDataUploadVideo--" +
                "\n" + "currentOutputVideoPath::" + currentOutputVideoPath + "\n"
                + "carsInforModel:" + carsInforModel.toString() + "\n"
                + "url:" + carsInforModel.getPath() + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrqw.getBytes());
        OkGo.<String>post(carsInforModel.getPath())
//                .isMultipart(true)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(video_url_path))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }

                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        String str = "totalSize:" + progress.totalSize +
                                "currentSize:" + progress.currentSize +
                                "date:" + progress.date +
                                "fraction:" + String.valueOf(progress.fraction) +
                                "exception:" + progress.exception;
                        UtilsLog.e("上传视频==uploadProgress====" + str);
                        UtilsLog.e("上传视频==uploadProgress====" + (progress.fraction * 100) + "%");
                        String logStr = "\n" + "上传视频==uploadProgress====" +
                                "\n" + "uploadProgress::" + str + "\n"
                                + "Progress::" + progress.toString();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        carsInforModel.setProgress(progress.fraction);
                        carsInforModel.save();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String logStrf = "\n" + "onDestroy-----FirstActivity-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
//        unBindService();
    }

    //绑定服务
    public void bindService() {
        //绑定服务
        bindService(new Intent(this, MyUploadService.class), conn, flags);
    }

    //解绑服务
    public void unBindService() {
        //防止在没有绑定的情况下，去解除绑定，抛出异常
        try {
            //解除绑定
            unbindService(conn);
        } catch (Exception e) {
            System.out.println("FFmpegActivity.unBindService" + e);
        }
    }

    //服务绑定的连接对象
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    //服务绑定的标识
    //BIND_AUTO_CREATE 绑定的同时，启动Service
    private int flags = Service.BIND_AUTO_CREATE;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionChecker.PERMISSION_REQUEST_CODE:
                if (permissionChecker.hasAllPermissionsGranted(grantResults)) {
                    // 执行你的相关操作
//                    if(type == 1){
//                        startAudio();
//                    }else if(type == 2){
//                        startVideo();
//                    }
                } else {
                    // 权限拒绝后的提示
                    permissionChecker.showDialog();
                }
                break;
        }
    }

    Uri fileUri = null;

    //  用户权限过滤
    boolean userRightCheckMode(int CHECK_MODE) {
        if (UserAccountModel_model == null)
            return false;

        boolean Is_exist = false;
        String userRight = UserAccountModel_model.getUserRight();
        UtilsLog.e("userRight==" + userRight);
        switch (CHECK_MODE) {
            case 3:
                //外检员
                if (userExistright(userRight, "0") || userExistright(userRight, "3")
                        || userExistright(userRight, "d") || userExistright(userRight, "D")) {
                    Is_exist = true;
                }
                break;
            case 4:
                //底盘动态
                if (userExistright(userRight, "0") || userExistright(userRight, "4")) {
                    Is_exist = true;
                }
                break;
            case 6:
                //路试
                if (userExistright(userRight, "0") || userExistright(userRight, "6")) {
                    Is_exist = true;
                }
                break;
            case 5:
                //底盘静态
                if (userExistright(userRight, "0") || userExistright(userRight, "5")) {
                    Is_exist = true;
                }
                break;
            case 7:
                //调度员
                if (userExistright(userRight, "0") || userExistright(userRight, "7")) {
                    Is_exist = true;
                }
                break;
        }
        return Is_exist;
    }

    //判断是否有对应的权限，有:true,否:false
    boolean userExistright(String userright, String right) {
        boolean is_userExistright = false;
        if (userright.contains(right)) {
            is_userExistright = true;
        }
        return is_userExistright;
    }

    @OnClick({R.id.ac_first_waijian, R.id.ac_first_dipandongtai,
            R.id.ac_first_lushi, R.id.ac_first_setting,
            R.id.ac_first_digou_item, R.id.ac_first_digou})
    public void onViewClicked(View view) {
        Intent intent = null;
        String logStr = "\n" + "---FirstActivity----onViewClicked---" +
                "\n" + "userRightCheckMode::";
        switch (view.getId()) {
            case R.id.ac_first_waijian:
//                intent = new Intent(instance, LoginActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                CHECK_MODE_CURRENT = 3;//外检员
                if (userRightCheckMode(CHECK_MODE_CURRENT)) {
                    intent = new Intent(instance, DaiJianCarsActivity.class);
                    intent.putExtra("userRightCheckMode", true);
                }
                logStr += userRightCheckMode(CHECK_MODE_CURRENT) + "\n";
                break;
            case R.id.ac_first_dipandongtai:
//                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 2;
                CHECK_MODE_CURRENT = 4;//底盘动态
                if (userRightCheckMode(CHECK_MODE_CURRENT)) {
                    intent = new Intent(instance, DaiJianCarsActivity.class);
                    intent.putExtra("userRightCheckMode", false);
                }
                logStr += userRightCheckMode(CHECK_MODE_CURRENT) + "\n";
                break;
            case R.id.ac_first_lushi:
//                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 1;
                CHECK_MODE_CURRENT = 6;//路试
                if (userRightCheckMode(CHECK_MODE_CURRENT)) {
                    intent = new Intent(instance, DaiJianCarsActivity.class);
                    intent.putExtra("userRightCheckMode", false);
                }
                logStr += userRightCheckMode(CHECK_MODE_CURRENT) + "\n";
                break;
            case R.id.ac_first_setting:
//                intent = new Intent(instance, SettingActivity.class);地沟
//                intent = new Intent(instance, DaiJianCarsActivity.class);
                BaseApplication.JIANCE_MODE = 6;
                CHECK_MODE_CURRENT = 5;//底盘静态
                if (userRightCheckMode(CHECK_MODE_CURRENT)) {
                    intent = new Intent(instance, DaiJianCarsActivity.class);
                    intent.putExtra("userRightCheckMode", false);
                }
                logStr += userRightCheckMode(CHECK_MODE_CURRENT) + "\n";
                break;
            case R.id.ac_first_digou_item:
                //调度
//                intent = new Intent(instance, DiaoDuActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                CHECK_MODE_CURRENT = 7;//调度员
                if (userRightCheckMode(CHECK_MODE_CURRENT)) {
                    intent = new Intent(instance, DiaoDuActivity.class);
                    intent.putExtra("userRightCheckMode", false);
                }
                logStr += userRightCheckMode(CHECK_MODE_CURRENT) + "\n";
                break;
            case R.id.ac_first_digou:
                //设置
                intent = new Intent(instance, SettingActivity.class);
//                BaseApplication.JIANCE_MODE = 0;
                break;
        }

        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        if (intent != null) {
            intent.putExtra("check_mode", BaseApplication.JIANCE_MODE);
            intent.putExtra("login_UserID", Login_name);

            UtilsLog.e("getDataToLogin-login_IDNumber==" + login_IDNumber);
            intent.putExtra("login_IDNumber", login_IDNumber);
            startActivity(intent);
        } else {
            TipDialog.show(instance, "没有权限，请联系管理员", TipDialog.TYPE.WARNING);
        }
    }

    private long exitTime = 0;

    // 双击返回退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                BaseApplication.getSelf().exit(this);
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
